package tzy.viewpager;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RectShape;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by Administrator on 2018/3/26.
 */

public class IndicateViewPager extends ViewPager {
    private static final int POINTS_MARGIN = 10;//默认指示器的间距
    private static final int MARGIN_BOTTOM = 13;//默认指示器到底部的距离
    private int mSpace;//间距px
    private int mBottomDistance;//底部距离px

    private Drawable mSelectedDrawable;//指示器被选中的drawable
    private Drawable mUnSelectedDrawable;//指示器未被被选中的drawable
    private Rect mSelectedRect;
    private Rect mUnSelectedRect;
    final Paint mPointPaint;

    public IndicateViewPager(Context context) {
        this(context, null);
    }

    public IndicateViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        mPointPaint = new Paint();
        mPointPaint.setAntiAlias(true);
        final float density = getResources().getDisplayMetrics().density;
        mSpace = (int) (density * POINTS_MARGIN);
        mBottomDistance = (int) (density * MARGIN_BOTTOM);
        addOnAdapterChangeListener(new OnAdapterChangeListener() {
            @Override
            public void onAdapterChanged(@NonNull ViewPager viewPager, @Nullable PagerAdapter oldAdapter, @Nullable PagerAdapter newAdapter) {


                if (newAdapter instanceof IndicatePagerAdapter) {
                    mSelectedDrawable = ((IndicatePagerAdapter) newAdapter).getIndicateResource(getContext());
                    mUnSelectedDrawable = ((IndicatePagerAdapter) newAdapter).getUnIndicateResource(getContext());
                    if (mSelectedDrawable != null) {
                        mSelectedRect = new Rect(mSelectedDrawable.getBounds());
                    }
                    if (mUnSelectedDrawable != null) {
                        mUnSelectedRect = new Rect(mUnSelectedDrawable.getBounds());
                    }
//                    fillRect(mSelectedRect == null ? mSelectedRect = new Rect() : mSelectedRect, mSelectedDrawable);
//                    fillRect(mUnSelectedRect == null ? mUnSelectedRect = new Rect() : mUnSelectedRect, mUnSelectedDrawable);

                } else {
                    mSelectedDrawable = null;
                    mUnSelectedDrawable = null;

                }

            }
        });
    }
//    private void fillRect(Rect rect, Drawable drawable) {
//        final float scale = (float) mPointHeight / drawable.getIntrinsicHeight();
//        rect.set(0, 0, (int) (scale * drawable.getIntrinsicWidth()), (int) (scale * drawable.getIntrinsicHeight()));
//    }

    /**
     * @param bottomDistance 距离底部的距离 px
     * @param space          指示器之间的间距
     */

    public void setDistance(int bottomDistance, int space) {
        mBottomDistance = bottomDistance;
        mSpace = space;
        invalidate();
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);
        final PagerAdapter adapter = getAdapter();

        if (mSelectedDrawable == null || mUnSelectedDrawable == null || adapter == null)
            return;
        final int curr = getAdapterCurrentItem();
        final int count = getAdapterCount();


        if (count > 1) {
            int points_width = (count - 1) * mUnSelectedDrawable.getBounds().width() + mSelectedDrawable.getBounds().width();
            int space_width = (count - 1) * mSpace;
            int curLeftEdge = (getWidth() - points_width - space_width) / 2;
            int curPosition = 0;
            final int y = getHeight() - mBottomDistance;
            while (curLeftEdge < getWidth() && curPosition < count) {
                final Rect currRect;
                if (curr == curPosition) {
                    currRect = mSelectedRect;
                    currRect.offsetTo(curLeftEdge + getScrollX(), y);

                    mSelectedDrawable.setBounds(currRect);
                    mSelectedDrawable.draw(canvas);

                } else {
                    currRect = mUnSelectedRect;
                    currRect.offsetTo(curLeftEdge + getScrollX(), y);
                    mUnSelectedDrawable.setBounds(currRect);
                    mUnSelectedDrawable.draw(canvas);

                }


                ++curPosition;
                curLeftEdge += (currRect.width() + mSpace);
            }

        }
    }

    public int getAdapterCurrentItem() {
        return getCurrentItem();
    }

    public int getAdapterCount() {
        final PagerAdapter adapter = getAdapter();
        return adapter == null ? 0 : adapter.getCount();
    }

    public abstract static class IndicatePagerAdapter<T> extends PagerAdapter {
        protected List<T> mData;
        private Deque<View> mCaches = new LinkedList<>();

        public IndicatePagerAdapter(List<T> data) {
            mData = data;
        }

        public void refreshData(List<T> data) {
            mData = data;
            notifyDataSetChanged();
        }


        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
//        super.destroyItem(container, position, object);
            mCaches.add((View) object);
//                container.removeView((View) object);
            container.removeView((View) object);
        }


        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = getView(container, mCaches.pollFirst(), position);
            container.addView(view);
            return view;
        }

        public abstract View getView(ViewGroup container, View convertView, int position);


        public T getItem(int p) {
            return mData == null ? null : mData.get(p);
        }

        @Override
        public int getCount() {
            return mData == null ? 0 : mData.size();
        }

        protected OnPageItemClickListener onPageItemClickListener;

        public void setOnPageItemClickListener(OnPageItemClickListener onPageItemClickListener) {
            this.onPageItemClickListener = onPageItemClickListener;
        }

        public interface OnPageItemClickListener {
            void onPageItemClick(ViewPager viewPager, View view, int position);
        }


        public abstract Drawable getIndicateResource(Context context);

        public abstract Drawable getUnIndicateResource(Context context);
    }

    public static class SimpleIndicatePagerAdapter<T> extends IndicatePagerAdapter<T> {

        private static final int INDICATE_WIDTH = 12;//ViewPager指示器的宽度
        private static final int INDICATE_HEIGHT = 2;//ViewPager指示器的高度
        private Context mContext;

        public SimpleIndicatePagerAdapter(Context context, List<T> data) {
            super(data);
            mContext = context;
        }

        @Override
        public View getView(ViewGroup container, View convertView, int position) {
            return null;
        }

        /**
         * 创建指示器被选中的Drawable
         */
        @Override
        public Drawable getIndicateResource(Context context) {
            //矩形形状


            RectShape rectShape = new RectShape();
            ShapeDrawable drawable2 = new ShapeDrawable(rectShape);

            drawable2.getPaint().setColor(Color.RED);
            drawable2.getPaint().setStyle(Paint.Style.FILL);
            drawable2.setBounds(0, 0, (int) (context.getResources().getDisplayMetrics().density * INDICATE_WIDTH), (int) (context.getResources().getDisplayMetrics().density * INDICATE_HEIGHT));
            return drawable2;
        }

        /**
         * 创建指示器未被选中的Drawable
         */
        @Override
        public Drawable getUnIndicateResource(Context context) {
            //矩形形状


            RectShape rectShape = new RectShape();
            ShapeDrawable drawable2 = new ShapeDrawable(rectShape);
            drawable2.getPaint().setColor(Color.WHITE);

            drawable2.getPaint().setStyle(Paint.Style.FILL);
            drawable2.setBounds(0, 0, (int) (context.getResources().getDisplayMetrics().density * INDICATE_WIDTH), (int) (context.getResources().getDisplayMetrics().density * INDICATE_HEIGHT));

            return drawable2;
        }
    }

}
